package com.spancer.gateway.autoPredicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * author by: mars
 * Date: 2020/11/5 11:06
 * Description: xxxRoutePredicateFactory,即xxx是配置的规则名
 */
@Component
public class TimeBetweenRoutePredicateFactory extends AbstractRoutePredicateFactory<TimeBetweenRoutePredicateFactory.Config> {

    public TimeBetweenRoutePredicateFactory() {
        super(TimeBetweenRoutePredicateFactory.Config.class);
    }

    // 控制配置类和配置文件的映射关系
    @Override
    public List<String> shortcutFieldOrder() {
        // 写入参数顺序
        return Arrays.asList("start","end");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        LocalTime start = config.getStart();
        LocalTime end = config.getEnd();

        //new Predicate<ServerWebExchange>(){
        //
        //    @Override
        //    public boolean test(ServerWebExchange serverWebExchange) {
        //        return false;
        //    }
        //};
        // 以下写法为匿名内部类的lambda表达
        return (exchange)-> {
            LocalTime now = LocalTime.now();
            return now.isAfter(start) && now.isBefore(end);
        };
    }

    public static class Config {
        private LocalTime start;
        private LocalTime end;

        public Config() {}

        public LocalTime getStart() {
            return start;
        }

        public void setStart(LocalTime start) {
            this.start = start;
        }

        public LocalTime getEnd() {
            return end;
        }

        public void setEnd(LocalTime end) {
            this.end = end;
        }
    }

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        System.out.println(formatter.format(LocalTime.now()));
    }
}
